const express = require("express")
const router = require("./router")
const app = express()
const bodyParser = require("body-parser")
const swaggerInstall = require('./utils/swagger')

//挂载swagger
swaggerInstall(app)

//设置跨域
app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma,Authorization ,Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    // Authorization 就是你自己设定的值，也可以直接换成token  //跨域时默认不暴露自定义的headers
    res.header("Access-Control-Expose-Headers","Authorization");

    next();
});

//鉴定token
app.use((req, res, next) => {
    const token = req.headers["authorization"]?.split(" ")[1]
    if (req.url == '/user/login') {
        next()
        return
    }
    //  else {
    //     const token = req.headers["authorization"]?.split(" ")[1]
    //     !token && res.status(401).send({ errCode: "-1", errorInfo: "token过期" })
    // }
    next()
})

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));//解析post请求数据
//挂载express router
app.use(router)

app.listen(9999, () => {
    console.log("服务器启动");
})